﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using UCL.Powersource;

namespace PowersourceUIToolkit.Test
{
    class TestBootstrapper : PowersourceBootstrapperBase
    {

        private CompositionContainer container;

        protected override object GetInstance(Type serviceType, string key)
        {
            string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
            var exports = container.GetExportedValues<object>(contract);

            if (exports.Count() > 0)
                return exports.First();

            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }

        protected override IEnumerable<object> GetAllInstances(Type serviceType)
        {
            return container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
        }

        protected override void Configure()
        {
            Debug.WriteLine("[{0}] : Configure", this);
            var catalog = new AggregateCatalog(
                    AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()
                    );

            container = new CompositionContainer(catalog);


            var batch = new CompositionBatch();

            batch.AddExportedValue<IUIManager>(new UIManager());
            //batch.AddExportedValue<IEventAggregator>(new EventAggregator());
            batch.AddExportedValue<ILog>(LogManager.GetLog(null));
            batch.AddExportedValue(container);
            batch.AddExportedValue(catalog);
            container.Compose(batch);
        }

        protected override void BuildUp(object instance)
        {
            container.SatisfyImportsOnce(instance);
        }

        protected override IEnumerable<System.Reflection.Assembly> SelectAssemblies()
        {
            return new[] { Assembly.GetExecutingAssembly() };
        }

        protected override void InitializeIoCDependants()
        {
            return;
        }

        protected override bool ValidateAssembly(string assemblyFilename)
        {
            return true;
        }
    }
}
